package com.gmcas.realm;

import com.gmcas.dao.UserMapper;
import com.gmcas.dao.entity.User;
import com.gmcas.service.UserService;
import com.gmcas.utils.Constant;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by zhangshuai on 2017/9/15.
 *  AuthorizingRealm 是认证与授权用户的类,
 *      其继承关系:Realm->CachingRealm->AuthenticatingRealm->AuthorizingRealm
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    /**
     * 授权用户
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     *  认证用户,验证用户是否合法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //获取用户名
        String username = (String)authenticationToken.getPrincipal();
        User user = userService.selectByUsername(username);
        //当前用户是否存在
        if(user == null){
            throw new UnknownAccountException("用户名不存在");
        }
        //确认当前用户的用户状态
        if(user.getUserStatus() == Constant.User.USER_STATUS_LOCK){
            throw new LockedAccountException("当前用户已锁定");
        }
        //返回用户的认证信息
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user.getUsername(),
                user.getPassword(),
                ByteSource.Util.bytes(user.getCredentialsSalt()),   //盐与用户名
                getName()
        );
        return authenticationInfo;
    }
}
